package com.itljm.cxrMarket.controller;

import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.entity.SysUser;
import com.itljm.cxrMarket.entity.dto.PhoneDetailDTO;
import com.itljm.cxrMarket.entity.dto.UserLoginDTO;
import com.itljm.cxrMarket.entity.dto.UserLoginVO;
import com.itljm.cxrMarket.service.SysUserService;
import com.itljm.cxrMarket.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author ljm
 * @date 2024/12/10 18:18
 */
@RestController
@RequestMapping("/wx")
@Slf4j
@CrossOrigin
public class WxController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private JwtUtil jwtUtil;

    @RequestMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO) {
        SysUser user = sysUserService.wxLogin(userLoginDTO);
        if (user == null) {
            return Result.fail("登录失败");
        }
        //为微信用户生成jwt令牌
        String jwt = jwtUtil.generateAccessToken(user.getOpenId());

        //封装返回的UserLoginVo
        UserLoginVO userLoginVo = UserLoginVO.builder()
                .userId(user.getId().toString())
                .openId(user.getOpenId())
                .nickName(user.getName())
                .avatarUrl(user.getAvatar())
                .token(jwt)
                .build();
        return Result.ok(userLoginVo);
    }

    // 获取手机号
    @RequestMapping("/getPhone")
    public Result getPhoneNumber(@RequestBody PhoneDetailDTO pdd) {
        String phone = sysUserService.getPhoneNumber(pdd.getCode());
        if (phone == null) {
            return Result.fail("获取手机号失败");
        }
        return Result.ok("获取成功",phone);
    }

    /**
     * 获取个人信息
     */
    @GetMapping("/profile/{id}")
    public Result<SysUser> profile(@PathVariable Long id) {
        SysUser sysUser = sysUserService.selectById(id);
        return Result.ok(sysUser);
    }

    // 保存个人信息
    @RequestMapping("/saveUserInfo")
    public Result saveUserInfo(@RequestBody SysUser user) {
        boolean b = sysUserService.updateById(user);
        if (!b) {
            return Result.fail("保存失败");
        }
        return Result.ok("保存成功");
    }
}
